package com.gxa.component.task;

import com.gxa.component.cache.LocalCache;
import com.gxa.mapper.system.PermMapper;
import com.gxa.pojo.vo.system.UserPermVO;
import com.gxa.utils.Constants;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class PermTask {
    @Resource
    private PermMapper permMapper;
    @Resource
    private LocalCache localCache;

    //每隔30秒执行一次
    @Scheduled(cron = "0 0/5 * * * ?")
    public void execute() {

        //先清空本地缓存
        localCache.clear();

        //从数据库查询所有的权限并放到本地缓存中
        List<UserPermVO> perms = this.permMapper.queryPerms();
        for (UserPermVO userPermVO : perms) {
            //先从缓存中获取一次
            Set<String> permSet = (Set<String>) (localCache.get(Constants.LOCAL_CACHE_PREFIX + userPermVO.getUserId()));
            if (permSet != null) {
                permSet.add(userPermVO.getPerm());
            } else {
                permSet = new HashSet<>();
                permSet.add(userPermVO.getPerm());
            }
            localCache.setLocalCache(Constants.LOCAL_CACHE_PREFIX + userPermVO.getUserId(), permSet);
        }
        System.out.println("----查询了一次数据-----");
    }
}